package com.lihuinch.test.feishu.eventsubscribe.handler.impl;

import com.alibaba.fastjson.JSONObject;
import com.lihuinch.test.feishu.eventsubscribe.constant.TestConstants;
import com.lihuinch.test.feishu.eventsubscribe.handler.FeishuEventHandler;
import com.lihuinch.test.feishu.eventsubscribe.handler.request.FeishuEvenVerifyUrlParam;
import com.lihuinch.test.feishu.eventsubscribe.handler.response.FeishuEventVerifyUrlResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用于飞书验证服务器url请求。
 *
 * @author lihu
 * @date 2021-8-27 16:16
 * @since
 */
@Service(FeishuEventHandler.FEI_SHU_EVENT_HANDLER + "_" + TestConstants.FeishuEvent.VERIFY_URL)
public class FeishuEventVerifyUrlHandler implements FeishuEventHandler<FeishuEventVerifyUrlResponse> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public FeishuEventVerifyUrlResponse handleEvent(JSONObject param) {

        FeishuEvenVerifyUrlParam feishuEvenVerifyUrlParam = JSONObject.toJavaObject(param, FeishuEvenVerifyUrlParam.class);

        String verificationToken = TestConstants.verificationToken;

        String token = feishuEvenVerifyUrlParam.getToken();
        String challenge = feishuEvenVerifyUrlParam.getChallenge();

        if (!Objects.equals(token, verificationToken)) {
            throw new RuntimeException("token校验失败");
        }

        return new FeishuEventVerifyUrlResponse(challenge);
    }
}
